import vobject, datetime
import xml.dom
from xml.dom import minidom
import codecs

class tudumo:
	def __init__(self, tudumoXml, tudumoIcs):
		self.file = tudumoXml
		self.dom = ''
		self.cal = calendrier(tudumoIcs)
	
	def read(self):
		self.dom = minidom.parse(self.file)
	
	def show(self):
		print self.dom.toprettyxml()
	
	def find(self):
		tasks = self.dom.getElementsByTagName('Task')

		for task in tasks:
			title = ''
			dueDate = ''
			for child in task.childNodes:
#				print child.nodeType+' - '+child.ELEMENT_NODE
				nodeType = "%s" %child.nodeType
				elementNode = "%s" %child.ELEMENT_NODE
#				print '-' + nodeType + '- | -' + elementNode + '-'
				if nodeType == elementNode:
#					print 'bon'
#					print child.tagName
					if child.tagName == 'Title':
						title = child.childNodes[0].data
					if child.tagName == 'DueDate':
						dueDate = child.childNodes[0].data
#				else:
#					print 'pas bon'

			if dueDate != '':
				print 'title:'+title
				print 'dueDate:'+dueDate
				day = int(dueDate[0:2])
				month = int(dueDate[3:5])
				year = int(dueDate[6:10])
				hour = int(dueDate[11:13])
				minute = int(dueDate[14:16])
				self.cal.addEvent(year, month, day, hour, title)

	def save(self):
		self.cal.write()

class calendrier:
	def __init__(self, file):
		self.file = file
		self.cal = vobject.iCalendar()
		self.cal.add('vevent')
	
	def read(self):
		f = open(self.file)
		stream = f.read()
		f.close()

		self.cal = vobject.readOne(stream)

	def show(self):
		self.cal.prettyPrint()
	
	def write(self):
		f = codecs.open(self.file, encoding='utf-8', mode='wb')
		stream = self.cal.serialize()
		f.write(stream)
		f.close()
	
	def populate(self):
		self.cal.add('vevent')
		v = self.cal.vevent
		utc = vobject.icalendar.utc
		v.add('dtstart').value = datetime.datetime(2007, 07, 12, 20, tzinfo=utc)
		v.add('dtend').value = datetime.datetime(2007, 07, 12, 21, tzinfo=utc)
		v.add('summary').value = 'hopla'
	
	def addEvent(self, year, month, day, hour, title):
		print year
		print month
		print day
		print hour
		print title
		
		hourEnd = hour+1

		if (hour == 23):
			hourEnd = 0

		v = self.cal.add('vevent')
		utc = vobject.icalendar.utc
		v.add('dtstart').value = datetime.datetime(year, month, day, hour, tzinfo=utc)
		v.add('dtend').value = datetime.datetime(year, month, day, hourEnd, tzinfo=utc)
		v.add('summary').value = title


if __name__ == '__main__':
	tudumoXml = 'c:\\program files\\thinkmo\\tudumo\\data\\Default_0.2.tudumo'
	tudumoIcs = 'c:\\gtd.ics'

	t = tudumo(tudumoXml, tudumoIcs)
	t.read()
	t.find()
	t.save()
